package cn.wangxl.group.rpc.netclient;

import cn.wangxl.group.rpc.discover.ServiceInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 网络客户端，NETTY实现
 * @Deacription NettyNetClient
 * @Author 20112128
 * @Date 2020/9/18 10:29
 **/
public class NettyNetClient implements NetClient{

    @Override
    public byte[] sendRequest(byte[] data, ServiceInfo serviceInfo) {

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        NettyClientHandler nettyClientHandler = new NettyClientHandler(data);
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(serviceInfo.getHost(),serviceInfo.getPort())
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .handler(new ChannelInitializer(){
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(nettyClientHandler);
                    }
                })
        ;

        try {
            // 开始连接
            ChannelFuture channelFuture = bootstrap.connect().sync();

            channelFuture.channel().closeFuture().sync();// 此处等待client端收到服务端返回数据关闭通道，否则rspData为空
            // send data
            byte[] rspData = nettyClientHandler.getReceiveData();

            return rspData;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                eventLoopGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
